package com.hg.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.hg.common.*;
import com.hg.exception.ServiceException;
import com.hg.mapper.RoleMapper;
import com.hg.mapper.RoleMenuMapper;
import com.hg.pojo.HgUser;
import com.hg.pojo.Menu;
import com.hg.pojo.Role;
import com.hg.pojo.RoleMenu;
import com.hg.pojo.dto.HgUserDTO;
import com.hg.pojo.dto.PageDTO;
import com.hg.service.HgUserService;
import com.hg.service.IMenuService;
import lombok.Data;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class HgUserController {

    @Autowired
    private HgUserService hgUserService;

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    private RedisTemplate redisTemplate;

    public static  String username = null;

    @PostMapping("/login")
    @CrossOrigin
    public R<HgUserDTO> login(@RequestBody HgUserDTO hgUserDTO, HttpServletRequest request){
        username = hgUserDTO.getUsername();
        HgUserDTO dto = null;
        String key = "login_" + username;
        redisTemplate.delete(key);
        dto = (HgUserDTO) redisTemplate.opsForValue().get(key);

        if (dto !=null){
            //如果存在，直接返回无需查询数据库
            return R.success(dto);
        }
        String username = hgUserDTO.getUsername();
        String password = hgUserDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return R.error(HttpStatus.CODE_ERROR, "参数错误");
        }

        dto = hgUserService.login(hgUserDTO);
        redisTemplate.opsForValue().set(key,dto,60, TimeUnit.MINUTES);
        return R.success(dto);
    }

    /**
     * 获取验证码
     * @param
     * @param response
     */
    @GetMapping(value = "/captcha", produces = "image/jpeg")
    public void captcha( HttpServletResponse response) {
// 定义response输出类型为image/jpeg类型
        response.setDateHeader("Expires", 0);
// Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
// return a jpeg
        response.setContentType("image/jpeg");

//-------------------生成验证码 begin --------------------------
//获取验证码文本内容
        String text = defaultKaptcha.createText();
//将验证码放入session中
        redisTemplate.opsForValue().set("captcha",text,60,TimeUnit.SECONDS);
        System.out.println(text);
//根据文本内容创建图形验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
//输出流输出图片，格式jpg
            ImageIO.write(image, "jpg", outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
//-------------------生成验证码 end ----------------------------
    }

  /*  @PostMapping("/register")
    public R<String> register(@RequestBody HgUser hgUser){
        if (hgUser == null){
            throw new ServiceException(HttpStatus.CODE_ERROR,"不能为空");
        }
        String password = hgUser.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        hgUser.setPassword(password);
        boolean save = hgUserService.save(hgUser);
        if (save){
            //注册成功
            return R.success(HttpStatus.REGISTER_SUCCESS,"注册成功");
        }else {
            throw new ServiceException(HttpStatus.REGISTER_ERROR,"注册失败");
        }
    }*/

    @GetMapping("/logout")
    public R<String> logout(HttpServletRequest request){

        return R.success(HttpStatus.LOGOUT_SUCCESS,"退出成功");
    }

    @PostMapping("/save")
    public R<String> save(@RequestBody HgUser hgUser){
        if (hgUser == null){
            throw new ServiceException(HttpStatus.CODE_ERROR,"不能为空");
        }
        String password = hgUser.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        hgUser.setPassword(password);

        boolean save = hgUserService.save(hgUser);
        if (save){
            redisTemplate.delete("user_page_" + username);
            //新增成功
            return R.success(HttpStatus.REGISTER_SUCCESS,"新增成功");
        }else {
            throw new ServiceException(HttpStatus.REGISTER_ERROR,"新增失败");
        }
    }

    //更新
    @PostMapping("/update")
    public R<String> update(@RequestBody HgUser hgUser){
        boolean update = hgUserService.updateById(hgUser);
        if (update){
            //编辑成功
            //删除缓存，然后重新加载缓存
            redisTemplate.delete("user_page_" + username);
            return R.success(HttpStatus.REGISTER_SUCCESS,"编辑成功");
        }else {
            throw new ServiceException(HttpStatus.REGISTER_ERROR,"编辑失败");
        }
    }
    //删除
    @DeleteMapping("/del/{id}")
    public R<String> delete(@PathVariable Long id){
        //先查出来进行逻辑删除
        HgUser hgUser = hgUserService.getById(id);
        hgUser.setIsDelete(1);
        //保存
        boolean delete = hgUserService.updateById(hgUser);
        if (delete){
            redisTemplate.delete("user_page_" + username);
            return R.success(HttpStatus.DELETE_SUCCESS,"删除成功");
        }else {
            return R.error(HttpStatus.DELETE_ERROR,"删除失败");
        }
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PostMapping("/del/batch")
    public R<String> deleteBatch(@RequestBody List<String> ids) {

        //通过id查询出所有要删除的用户
        try {
            for (String id : ids) {
                HgUser user = hgUserService.getById(id);
                //进行逻辑删除
                user.setIsDelete(1);
                hgUserService.updateById(user);
            }
            redisTemplate.delete("user_page_" + username);
            return R.success(HttpStatus.DELETE_SUCCESS,"删除成功");
        } catch (Exception e) {
            throw new ServiceException(HttpStatus.DELETE_ERROR,"删除失败");
        }


    }

    /**
     * 获取当前用户信息
     * @param username
     * @return
     */
    @GetMapping("/username/{username}")
    public R<HgUser> findByUsername(@PathVariable String username) {
        QueryWrapper<HgUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return R.success(HttpStatus.PAGE_SUCCESS,hgUserService.getOne(queryWrapper));
    }


    /**
     * 分页查询用户
     * @param pageDTO
     * @return
     */
    @GetMapping("/page")
    public R<com.baomidou.mybatisplus.extension.plugins.pagination.Page> page(PageDTO pageDTO){
        Page<HgUser> hgUserPage = null;
        String key = "user_page_" + username;
        redisTemplate.delete(key);
        hgUserPage = (Page<HgUser>) redisTemplate.opsForValue().get(key);
        if (hgUserPage != null){
            return R.success(HttpStatus.PAGE_SUCCESS,hgUserPage);
        }

        hgUserPage = hgUserService.UserPage(pageDTO);
        redisTemplate.opsForValue().set(key,hgUserPage,60,TimeUnit.MINUTES);
        return R.success(HttpStatus.PAGE_SUCCESS,hgUserPage);
    }

    /**
     * 导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<HgUser> list = hgUserService.list();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("nickname", "昵称");
        writer.addHeaderAlias("sex", "性别");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("status", "状态");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

}